import React, { useEffect, useRef, useState } from "react"
import type { ReactNode } from "react"
import { Button, message, Slider } from "antd"
import axios from "axios"
import "./index.less"
import PdfView from "@/components/PdfView"
interface Iprops {
	children?: ReactNode
	width?: string
	height?: string
	type: string
}
interface Files {
	name: string
	link: string
	file: File
	progress: number
}
const Upload: React.FC<Iprops> = (props) => {
	const { width = "1000px", height = "320px", type } = props
	const inputRef = useRef<HTMLInputElement>(null)
	// const [progress, setProgress] = useState<number>(0)
	const [fileList, setFileList] = useState<Array<Files>>([])
	const [count, setCount] = useState<number>(0)
	const [flag, setFlag] = useState<boolean>(false)
	const [link, setLink] = useState<string>("")
	useEffect(() => {
		if (fileList.length > 0 && count === fileList.length) {
			setCount(0)
			setFlag(false)
			inputRef.current!.value = ""
		}
	}, [count])
	const handleUpload = (e: any) => {
		setFlag(true) // 异步更新
		const files = e.target.files ? e.target.files : e.dataTransfer.files
		if (flag) {
			message.error({
				content: "上份传输任务还未完成，请勿重复操作😆😆😆",
			})
			return
		}
		console.log(files)
		if (!preCheck(files)) {
			message.error({
				content: "仅支持上传pdf文件😆😆😆",
			})
			return
		}
		const baseurl =
			files.length > 1 ? "https://file.io/~/" : "https://file.io/?title="
		const keys = Object.keys(files).filter((key) => !isNaN(Number(key)))
		const filels = keys.map((key) => {
			const name = files[key].name
			return {
				name,
				link: "",
				file: files[key],
				progress: 0,
			}
		})
		setFileList(filels)
		keys.forEach((key) => {
			const url = baseurl + encodeURIComponent(files[key].name)
			upload(url, files[key])
		})
	}
	// 上传前所有文件校验
	const preCheck = (files: any) => {
		const keys = Object.keys(files).filter((key) => !isNaN(Number(key)))
		for (let i = 0; i < keys.length; i++) {
			const key = keys[i]
			if (!access(files[key])) {
				return false
			}
		}
		return true
	}
	// 上传文件类型检测
	const access = (file: File) => {
		return file.type === type
	}
	// 上传文件
	const upload = (url: string, file: File) => {
		const formDate = new FormData()
		formDate.append("file", file)
		axios
			.post(url, formDate, {
				onUploadProgress: (progressEvent: any) => {
					// 计算上传进度
					const percentCompleted = Math.round(
						(progressEvent.loaded * 100) / progressEvent.total,
					)

					// setFileList(newList)
					setFileList((fileList) => {
						const index = fileList.findIndex((it) => it.name === file.name)
						const newList = [...fileList]
						newList[index].progress = percentCompleted
						return newList
					})
					console.log(`Upload Progress: ${percentCompleted}%`)
				},
			})
			.then((response) => {
				setCount((count) => count + 1)
				setFileList((fileList) => {
					const index = fileList.findIndex((it) => it.name === file.name)
					const newList = [...fileList]
					newList[index].link = response.data.link
					return newList
				})
				// 上传完成时处理响应
				// inputRef.current!.value = ""
				console.log(response)
			})
			.catch((error) => {
				console.error("Error:", error)
			})
	}
	// 点击按钮回调
	const btnHandle = () => {
		inputRef.current?.click()
	}
	const handleDrop = (e: any) => {
		e.stopPropagation()
		e.preventDefault()
		handleUpload(e)
	}
	const handleDragover = (e: any) => {
		e.stopPropagation()
		e.preventDefault()
		e.dataTransfer.dropEffect = "copy"
	}
	// 预览
	const preview = (file: File) => {
		const link = URL.createObjectURL(file)
		console.log(link)
		setLink(link)
	}
	return (
		<>
			<div
				className="upload-container"
				style={{ width: width, height: height }}
			>
				<div className="btn-upload">
					<Button type="primary" onClick={btnHandle}>
						点击上传
					</Button>
				</div>
				<input
					ref={inputRef}
					className="upload-input"
					type="file"
					accept={type}
					onChange={handleUpload}
					multiple
				/>
				<div
					className="drop"
					onDrop={handleDrop}
					onDragOver={handleDragover}
					onDragEnter={handleDragover}
				>
					<i className="el-icon-upload" />
					<span>将文件拖到此处</span>
				</div>
			</div>
			{fileList.map((item, index) => {
				return (
					<div className="progress" key={index} style={{ width: width }}>
						<span className="single title">{item.name}</span>
						<Slider
							className="slider"
							step={0.5}
							tooltip={{ formatter: null }}
							value={item.progress}
						/>
						<Button
							className="button"
							size="small"
							disabled={item.progress !== 100}
							onClick={() => preview(item.file)}
						>
							查看
						</Button>
					</div>
				)
			})}
			{link !== "" && <PdfView link={link} />}
		</>
	)
}
export default Upload
